﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.Entities.ExcelColumns
{
    public enum ExcelColumnsType
    {
        Text,
        List,
        Date
    }

    public class ExcelColumn(string name, string? path = null, ExcelColumnsType type = ExcelColumnsType.Text)
    {
        public string name { get; set; } = name;
        public string path { get; set; } = path != null ? path : name;
        public ExcelColumnsType type { get; set; } = type;
        public static Object? GetPropValue(object obj, String path)
        {
            foreach (String part in path.Split('.'))
            {
                if (obj == null)
                {
                    return null;
                }

                Type type = obj.GetType();
                PropertyInfo info = type.GetProperty(part);

                if (info == null)
                {
                    return null;
                }

                obj = info.GetValue(obj, null);
            }
            return obj;
        }

        public static void setPropValue(object obj, String path, object value)
        {
            int i = 0;
            string[] paths = path.Split('.');
            foreach (String part in paths)
            {
                if (obj == null)
                {
                    return;
                }

                Type type = obj.GetType();
                PropertyInfo info = type.GetProperty(part);

                if (info == null)
                {
                    return;
                }

                if ( i == (paths.Count() - 1))
                {
                    switch(info.PropertyType.Name)
                    {
                        case "Nullable`1":
                            bool result = int.TryParse(value?.ToString(), out var number);
                            if (result)
                            {
                                info.SetValue(obj, number);
                            }
                            break;
                        default:
                            info.SetValue(obj, value);
                            break;
                    }
                    
                    return;
                }
                i++;
                obj = info.GetValue(obj, null);
            }
        }
    }
}
